<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix='sec' uri='http://www.springframework.org/security/tags'%>
<%@ taglib prefix='s' uri='/struts-tags' %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="scripts/boot.js"></script>
<style type="text/css">
	ul{
		margin-left:25;padding:0;
 		list-style:none; 
	}
	.mini-checkboxlist-item{
		padding: 10px;
	}
	.Edit_Button, .Delete_Button, .Update_Button, .Cancel_Button
    {
        font-size:11px;color:#1B3F91;font-family:Verdana;  
        margin-right:5px;
    }
    .mini-radiobuttonlist-td
    {
    	height: 25px;
    }
</style>
</head>
<body>
	<fieldset style="border:solid 1px #aaa;padding:3px;">
		<legend >录入推荐客户信息</legend>
		<div id="form1" style="padding-left:5px;padding-bottom:7px;">
			<input name="customerId" class="mini-hidden" value="<s:property value='id'/>"/>
			<input name="callId" class="mini-hidden" value="<s:property value='callId'/>"/>
			<input name="callStatus" class="mini-hidden" value="<s:property value='callStatus'/>"/>
			<div class="mini-toolbar" style="border-bottom:0;padding:0px;">
	            <table style="width:100%;">
	                <tr>
	                    <td style="width:100%;">
	                    	<sec:authorize url='/customer_recommend_newrow.do'>
	                        <a class="mini-button" iconCls="icon-add" onclick="newRow()" plain="true">增加</a>
	                        </sec:authorize>
	                    </td>
	                </tr>
	            </table>           
        	</div>
            <div id="datagrid2" class="mini-datagrid" style="width:100%;height:auto;" showLoading="false" allowResize="false"
        		url="tel_info_view.do"  idField="id" showPager="false">
		        <div property="columns">
		            <div field="phoneNum" width="20%" headerAlign="center" >号码
		                <input property="editor" name="phoneNum" class="mini-textbox" style="width:100%;" required="true" vtype="int;rangeChar:7,12;numType"/>
		            </div>
		            <div type="comboboxcolumn" field="type" width="10%" headerAlign="center" >类型
		                <input property="editor" name="type" valueField="keyName" textField="keyValue" class="mini-combobox" style="width:100%;" url="dictionary_cm_key_val_view.do?typeName=CUSTOMER_PHONE_TYPE" required="true"/>                
		            </div>
		            <div type="comboboxcolumn" field="isMain" width="10%" headerAlign="center" >是否主要
		            	<input property="editor" name="isMain" class="mini-combobox" style="width:100%;" data="isMajor" required="true" />
		            </div>
		            <div field="remarks" width="35%" headerAlign="center" allowSort="true">备注
		                <input property="editor" name="remarks" class="mini-textbox" style="width:100%;"/>
		            </div>                              
		            <sec:authorize url='/customer_recommend_newrow_info.do'>
		            <div name="action" width="25%" headerAlign="center" align="center" renderer="onActionRenderer" cellStyle="padding:0;">操作</div>
		            </sec:authorize>
		        </div>
    		</div>
        </div>
		
		<div id="form2">
	        <input class="mini-hidden" name="id" value="<s:property value='id'/>"/>
	        <input name="callId" class="mini-hidden" value="<s:property value='callId'/>"/>
	        <input class="mini-hidden" id="contact_no" name="contactNo"/>
	        <table cellspacing="10" cellpadding="0">
	        	<tr>
		            <td align="right">姓名：</td>
		            <td style="width:250px;">    
		                <input name="name" style="width: 150px;" class="mini-textbox" required="true"/>
		            </td>
		            <td align="right">性别：</td>
		            <td >
		                <input name="sex" class="mini-radiobuttonlist" repeatItems="1" repeatLayout="table" repeatDirection="vertical" textField="keyValue" valueField="keyName"
		                	url="dictionary_cm_key_val_view.do?typeName=CUSTOMER_SEX_TYPE" onbeforeshowpopup="onbeforeshowpopup" value="10"/>
		            </td>
	        	</tr>
	        	<tr>
		            <td align="right">出生日期：</td>
		            <td >
		                <input name="birthDate" style="width: 150px;" class="mini-datepicker" emptyText="请选择日期"/>
		            </td>
		            <td align="right">客户级别：</td>
		            <td >    
		                <input name="customerLevel" style="width: 150px;" class="mini-combobox" valueField="keyName" textField="keyValue"
		                 	url="dictionary_cm_key_val_view.do?typeName=CUSTOMER_LEVEL_TYPE" value="1"/>
		            </td>
		        </tr>
		        <tr>
		        	<td align="right">客户来源：</td>
		        	<td>
		        		<input name="customersSource" id="customers_source" style="width: 150px;" valueField="keyName" textField="keyValue" class="mini-combobox"
		        		 url="dictionary_cm_key_val_view.do?typeName=CUSTOMER_SOURCE_TYPE" value="33"/>
		        	</td>
		        	<td align="right">是否邮寄期刊：</td>
		        	<td>
		        		<input name="journal" style="width: 150px;" valueField="keyName" textField="keyValue" class="mini-combobox"
		        		 url="dictionary_cm_key_val_view.do?typeName=CUSTOMER_MAIL_TYPE" value="14"/>
		        	</td>
		        </tr>
		        <tr>
		        	<td align="right">地址：</td>
		        	<td colspan="3">
		        		<input name="provinceId" id="province_val" class="mini-hidden"/>
		        		<input id="province" name="pName" class="mini-textbox" onfocus="focusP" emptyText="请选择省份" required="true"/>
		        		<input name="cityId" class="mini-hidden" id="city_val" />
		        		<input class="mini-textbox" name="cName" id="city" readOnly="true" emptyText="请选择城市" required="true"/>
		        		<input name="districtId" id="district_val" class="mini-hidden"/>
		        		<input class="mini-textbox" name="dName" id="district" readOnly="true" emptyText="请选择区县" required="true"/>
		        		<span>邮编：</span>
		        		<input class="mini-textbox" name="zipCode" style="width: 85px;" />
		        	</td>
		        </tr>
		        <tr>
		        	<td align="right">详细地址：</td>
		        	<td colspan="3">
		        		<input name="address" class="mini-textbox" style="width:384px;" />
		        	</td>
		        </tr>
		        <tr>
		        	<td align="right">会员信息：</td>
		            <td colspan="3"> 
		            	<span>余额：</span>   
		                <input name="money" class="mini-textbox" url="" style="width: 85px;"/>
		                <span>积分：</span>
		                <input name="redEnvelopes" class="mini-textbox" url="" style="width: 85px;"/>
		                <span>红包：</span>
		                <input name="integral" class="mini-textbox" url="" style="width: 85px;"/>
		            </td>
		        </tr>
		        <tr>
		            <td align="right">推荐人：</td>
		            <td>
		            	<input name="recommendId" id="recommend_id" emptyText="请选择推荐人" style="width: 150px;" class="mini-buttonedit" onbuttonclick="onButtonEdit" enabled="false"/>
		            </td>
		        </tr>
		        <tr>
		            <td align="right">备注：</td>
		            <td colspan="3">
		                <input name="remarks" class="mini-textarea" style="width:384px;" />
		            </td>
		        </tr>
	    	</table>
			<div style="text-align:center;padding-top:15px;">               
				<sec:authorize url='/customer_recommend_save.do'>
		        <a class="mini-button" onclick="onOk" style="width:100px;margin-right:20px;">保存客户信息</a>      
		        </sec:authorize>
		    </div>
		</div>
		<div id="win1" class="mini-window" allowDrag="false" showHeader="false" title="选择地址—省份" style="width: 300px;height: 150px;">
		</div>
		<div id="win2" class="mini-window" allowDrag="false" showHeader="false" title="选择地址—省份" style="width: 300px;height: 150px;">
		</div>
		<div id="win3" class="mini-window" allowDrag="false" showHeader="false" title="选择地址—省份" style="width: 300px;height: 150px;">
		</div>
	</fieldset>
<script type="text/javascript">
	mini.parse();
	var isSave = false;
	
	var form1 = new mini.Form("form1");
	var recommendId = mini.get("recommend_id");
	function SetData(data) {
		data = mini.clone(data);
		recommendId.setValue(data.recommendId);
		recommendId.setText(data.recommendName);
	}
	
/*-------号码增删改-------------------------------------------------*/
	var grid2 = mini.get("datagrid2");
	var callId = mini.getbyName("callId");
	grid2.load({callId: callId.getValue()});
	
	// 是否是主要号码-加载本地数据
	var isMajor = [{ id: 1, text: '是' }, { id: 0, text: '否'}];
	
	function onActionRenderer(e) {
        var grid2 = e.sender;
        var record = e.record;
        var uid = record._uid;
		
        var s = ' <a class="Edit_Button" href="javascript:editRow(\'' + uid + '\')" >修改</a>'
                + ' <a class="Delete_Button" href="javascript:delRow(\'' + uid + '\')">删除</a>';

        if (grid2.isEditingRow(record) && record.id == undefined) {
            s = '<a class="Update_Button" href="javascript:saveRow(\'' + uid + '\')">保存</a>'
                + '<a class="Cancel_Button" href="javascript:cancelRow(\'' + uid + '\')">取消</a>';
        }else if (grid2.isEditingRow(record) && record.id != undefined){
            s = '<a class="Update_Button" href="javascript:updateRow(\'' + uid + '\')">更新</a>'
                + '<a class="Cancel_Button" href="javascript:cancelRow(\'' + uid + '\')">取消</a>';
        }
        return s;
    }
	
	function newRow() {     
    	if(grid2.isEditing()) {
    		mini.alert("请先保存号码！");
    	}else {
    		if(grid2.getData().length == 4) {
    			mini.alert("每个客户最多可添加四个电话号码！");
    		}else {
		        var row = {};
		        grid2.addRow(row, 0);
		        grid2.beginEditRow(row);
    		}
    	}
    }
	
	function editRow(row_uid) {
        var row = grid2.getRowByUID(row_uid);
        if(grid2.isEditing()) {
        	mini.alert("请先保存号码！");
        }else {
	        if (row) {
	        	grid2.cancelEdit();
	        	grid2.beginEditRow(row);
	        }
        }
    }
	
	function cancelRow(row_uid) {            
		grid2.reload();
    }
	
	function delRow(row_uid) {
        var row = grid2.getRowByUID(row_uid);
        if(grid2.isEditing()) {
    		mini.alert("请先保存号码！");
   		}else {
   			if(grid2.getData().length > 1) {
   				if (row) {
   		            if (confirm("确定删除此记录？")) {
   		            	grid2.loading("删除中，请稍后......");
   		                $.ajax({
   		                    url: "tel_info_del.do?id=" + row.id,
   		                    dataType: "json",
   		                    success: function (text) {
   		                    	if(text.success){
   		                    		grid2.reload();
   		                   		}else{
   		                   			mini.alert("删除失败，id不能为空。");
   		                   		}
   		                    }
   		                });
   		            }
   		        }
   			}else{
   				mini.alert("请至少保留一个号码！");
   			}
        }
	}
	
	// 添加验证号码是否重复
    function checkNum(row_index, phoneNum) {
    	var data = grid2.getData();
    	var j = 0;
    	data.splice(row_index, 1);
    	for(var i in data){
	    	if(phoneNum == data[i].phoneNum) {
	    		j++;
	    	}
    	}
    	return j;
    }
	
    // 验证号码格式
   	mini.VTypes["numTypeErrorText"] = "号码格式不正确";
    mini.VTypes["numType"] = function (v) {
    	var reMobile = new RegExp("^0?1[34578]\\d{9}$");
    	var rePhone = new RegExp("^(010|02\\d|0[3-9]\\d{2})?\\d{7,8}$");
    	if(reMobile.test(v)) {
    		return true;
    	} else if(rePhone.test(v)) {
    		return true;
    	} else {
    		return false;
    	}
    }
	
    var form1 = new mini.Form("#form1");
    function saveRow(row_uid) {
        var row = grid2.getRowByUID(row_uid);
        var o = form1.getData(true);
        form1.validate();
	    if (form1.isValid() == false) return;
	    var i = checkNum(grid2.indexOf(row), o.phoneNum);
	    if(i == 1) {
	    	mini.alert("号码已存在，请重新添加！");
	    }else {
	    	if(mustHaveMain(o.phoneNum, o.isMain)) {
	    		if(checkMainNum(o.phoneNum, o.isMain)) {
		    		grid2.loading("保存中，请稍后......");
	    			$.ajax({
				        url: "tel_info_save.do",
						type: 'post',
						dataType: 'json',
				        data: o,
				        cache: false,
				        success: function (text) {
				            if(text.success){
				            	grid2.commitEditRow(row);
				            	grid2.reload();
				            }else{
				            	mini.alert("数据错误！");
				            }
				        },
				        error: function (jqXHR, textStatus, errorThrown) {
				            alert(jqXHR.responseText);
				            window.CloseOwnerWindow();
				        }
				    });
	    		} else {
	    			mini.alert("主要号码已存在");
	    		}
    		} else {
    			mini.alert("必须存在一个主要号码");
    		}
	    }
    }
    
    function updateRow(row_uid) {
        var row = grid2.getRowByUID(row_uid);
        var o = form1.getData(true);
        form1.validate();
	    if (form1.isValid() == false) return;
	    var i = checkNum(grid2.indexOf(row), o.phoneNum);
	    if(i == 1) {
	    	mini.alert("号码已存在，请重新修改！");
	    }else {
	        if(mustHaveMain(o.phoneNum, o.isMain)) {
	        	if(checkMainNum(o.phoneNum, o.isMain)) {
	        		grid2.loading("更新中，请稍后......");
		        	$.ajax({
				        url: "tel_info_edit.do?id=" + row.id,
						type: 'post',
						dataType: 'json',
				        data: o,
				        cache: false,
				        success: function (text) {
				            if(text.success){
				            	grid2.commitEditRow(row);
				            	grid2.reload();
				            }else{
				            	mini.alert("数据错误！(id不能为空)");
				            }
				        },
				        error: function (jqXHR, textStatus, errorThrown) {
				            alert(jqXHR.responseText);
				            window.CloseOwnerWindow();
				        }
				    });
	        	} else {
	        		mini.alert("主要号码已存在");
	        	}
	        } else {
	        	mini.alert("必须保留主要号码！");
	        } 
	    }
    }
    
    // 验证主要号码是否已存在
    function checkMainNum(phoneNum, isMain) {
    	var data = grid2.getData();
    	var flag = false;
    	if(isMain == 1) {
	    	for(var i in data) {
	    		if(data[i].isMain == 1) {
	    			flag = true;
	    			break;
	    		}
	    	}
	    	if(flag) {
    			return false;
    		} else {
    			return true;
    		}
    	} else {
    		return true;
    	}
    }
    
    // 验证主要号码必须存在
    function mustHaveMain(phoneNum, isMain) {
    	var data = grid2.getData();
    	var flag = false;
    	if(isMain == 0) {
    		for(var i in data) {
    			if(data[i].phoneNum != phoneNum && data[i].isMain == 1) {
    				flag = true;
    				break;
    			}
    		}
    		if(flag) {
    			return true;
    		} else {
    			return false;
    		}
    	} else {
    		return true;
    	}
    }

/*---客户信息-----------------------------------------------------------------------------------------------*/
	
	var form2 = new mini.Form("form2");
	
	// 弹出省份列表
 	var win1 = mini.get("win1");
 	var province = mini.get("province");
 	var provinceVal = mini.get("province_val");
 	function focusP(e) {
 		var el=e.sender.getEl();
		var bodyEl1 = win1.getBodyEl();
		$(bodyEl1).empty();
		$.post("customer_manage_find_province.do", {}, function(data) {
			win1.showAtEl(el, {
			   xAlign:"left",
			   yAlign:"below"
			});
			$.each(data, function(i, obj) {
				$(bodyEl1).append("</li><a href='javascript:loadC("+obj.id+", "+'"'+obj.pName+'"'+")' style='padding: 5px;'>"+obj.pName+"</a>");
			});
		}, "json");
		
 	}
 
 	// 通过省加载城市
 	var city = mini.get("city");
 	var cityVal = mini.get("city_val");
 	var win2 = mini.get("win2");
 	function loadC(p_id, p_name) {
 		var el = city.getEl();
		var bodyEl2 = win2.getBodyEl();
		$(bodyEl2).empty();
		$.post("customer_manage_find_city.do", {provinceId: p_id}, function(data) {
	 		provinceVal.setValue(p_id);
	 		province.setValue(p_name);
	 		win1.hide();
			win2.showAtEl(el, {
			   xAlign:"left",
			   yAlign:"below"
			});
			$.each(data, function(i, obj) {
				$(bodyEl2).append("<a href='javascript:loadD("+'"'+obj.id+'"'+", "+'"'+obj.cName+'"'+", "+'"'+obj.zipCode+'"'+")' style='padding: 5px;'>"+obj.cName+"</a>");
				mini.parse();
			});
		}, "json");
 	}
 	
 	// 通过城市加载区县
 	var win3 = mini.get("win3");
 	var district = mini.get("district");
 	var districtVal = mini.get("district_val");
 	var zipCode = mini.getbyName("zipCode");
 	function loadD(c_id, c_name, c_zipCode) {
 		var el = district.getEl();
 		var bodyEl3 = win3.getBodyEl();
 		zipCode.setValue(c_zipCode);
 		$(bodyEl3).empty();
 		$.post("customer_manage_find_district.do", {cityId: c_id}, function(data) {
 			city.setValue(c_name);
 			cityVal.setValue(c_id);
 			win2.hide();
 			win3.showAtEl(el, {
 			   xAlign:"left",
 			   yAlign:"below"
 			});
 			$.each(data, function(i, obj) {
				$(bodyEl3).append("<a href='javascript:setD("+obj.id+", "+'"'+obj.dName+'"'+")' style='padding: 5px;'>"+obj.dName+"</a>");
				mini.parse();
			});
 		}, "json");
 	}
 	
// 设置区县
 	function setD(d_id, d_name) {
 		win3.hide();
 		districtVal.setValue(d_id);
 		district.setValue(d_name);
 	}
    
    // 获取主要号码-用于生成任务
	var contactNo = mini.get("contact_no");
    function findMainTel(){
    	for(var i=0; i<grid2.getData().length; i++) {
    		if(grid2.getData()[i].isMain == 1) {
    			contactNo.setValue(grid2.getData()[i].phoneNum);
    		}
    	}
    }
    
	// 保存客户信息
    function onOk() {
    	if(grid2.isEditing()) {
    		mini.alert("请先保存号码！");
    	} else {
    		if(grid2.getData().length > 0) {
    		    findMainTel();
    			var o = form2.getData(true); 
    		    form2.validate();
    		    if (form2.isValid() == false) return;
    		    $.ajax({
    		        url: "customer_recommend_save.do",
    				type: 'post',
    				dataType: 'json',
    		        data: o,
    		        cache: false,
    		        success: function (text) {
    		            if(text.success){
    		            	isSave = true;
    		            	mini.alert("保存成功！");
    		            }else{
    		            	mini.alert("数据错误！");
    		            }
    		        },
    		        error: function (jqXHR, textStatus, errorThrown) {
    		            alert(jqXHR.responseText);
    		            window.CloseOwnerWindow();
    		        }
    		    });
    		} else {
    			mini.alert("客户号码不能为空！");
    		}
    	}
    }
	
	var customerId = mini.getbyName("customerId");
    function CloseWindow(action) {
		if(isSave) {
			action = {callId: callId.getValue(), customerId: customerId.getValue(), close: "save"};
		} else {
			action = {close: "cancle"};
		}
	    window.CloseOwnerWindow(action);
		
    }

</script>
</body>
</html>